package com.kakarote.hrm.task;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.kakarote.hrm.constant.*;
import com.kakarote.hrm.entity.PO.*;
import com.kakarote.hrm.entity.VO.*;
import com.kakarote.hrm.mapper.HrmDeptMapper;
import com.kakarote.hrm.mapper.HrmEmployeeMapper;
import com.kakarote.hrm.mapper.HrmRecruitPlanMapper;
import com.kakarote.hrm.service.*;
import com.kakarote.hrm.service.impl.HrmEmployeeTechnicalServiceImpl;
import com.kakarote.hrm.service.impl.HrmRecruitPositionServiceImpl;
import dataEncoder.DataEncoderFactory;
import dataEncoder.DataForEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 国资委数据同步
 *
 * @Author 92487
 * @Date 2024/10/20 15:39
 */
@Component
@EnableScheduling
@EnableAsync
@Slf4j
public class GzwEmployeeTask {

    @Value("${sync.sourceId}")
    private String sourceId;
    @Value("${sync.algorithm}")
    private String algorithm;
    @Value("${sync.secretKey}")
    private String secretKey;
    @Value("${sync.url.dept}")
    private String deptUrl;
    @Value("${sync.url.employee}")
    private String employeeUrl;
    @Value("${sync.url.post}")
    private String postUrl;
    @Value("${sync.url.education}")
    private String educationUrl;
    @Value("${sync.url.work}")
    private String workUrl;
    @Value("${sync.callbackUrl}")
    private String callbackUrl;
    @Value("${sync.url.plan}")
    private String plan;
    @Value("${sync.url.position}")
    private String position;
    @Value("${sync.url.startPlan}")
    private String record;
    @Value("${sync.url.startPosition}")
    private String startPosition;
    @Value("${sync.url.proces}")
    private String proces;
    @Value("${sync.url.user}")
    private String recruitUser;


    @Autowired
    private HrmEmployeeMapper employeeMapper;
    @Autowired
    private IHrmEmployeeDataService employeeDataService;
    @Autowired
    private HrmDeptMapper deptMapper;
    @Autowired
    private IHrmEmployeePostService certificateService;
    @Autowired
    private IHrmEmployeeEducationExperienceService educationExperienceService;
    @Autowired
    private HrmEmployeeTechnicalServiceImpl employeeTechnicalService;
    @Autowired
    private HrmRecruitPlanMapper recruitPlanMapper;
    @Autowired
    private HrmRecruitPositionServiceImpl recruitPositionService;
    @Autowired
    private IHrmRecruitPlanRecordService recruitPlanRecordService;
    @Autowired
    private IHrmRecruitStartPositionService recruitStartPositionService;
    @Autowired
    private IHrmRecruitProcesService recruitProcesService;
    @Autowired
    private IHrmRecruitUserService recruitUserService;

    /**
     * 招聘人员同步
     *
     * @return true-同步成功, false-同步失败
     */
    public boolean syncRecruitUser() {
        // 招聘人员列表
        List<HrmRecruitUser> recruitUserList = Optional.ofNullable(recruitUserService.lambdaQuery().list()).orElse(new ArrayList<>());

        // 岗位列表
        List<HrmRecruitPosition> positionList = Optional.ofNullable(recruitPositionService.lambdaQuery().list()).orElse(new ArrayList<>());
        Map<Long, String> positionMap = positionList.stream()
                .collect(Collectors.toMap(HrmRecruitPosition::getPositionId, HrmRecruitPosition::getPositionName, (v1, v2) -> v1));

        List<SyncRecruitUserVO> syncRecruitUserList = recruitUserList.stream().map(item -> {
            SyncRecruitUserVO syncUser = new SyncRecruitUserVO();
            syncUser.setPlanId(item.getPlanId().toString());
            syncUser.setStartPlanId(item.getRecordId().toString());
            syncUser.setProcesId(item.getProcesId() == null ? null : item.getProcesId().toString());
            syncUser.setPositionId(item.getPositionId().toString());

            // 查询岗位名称
            if (positionMap.containsKey(item.getPositionId())) {
                syncUser.setPositionName(positionMap.get(item.getPositionId()));
            }

            syncUser.setUserId(item.getUserId());
            syncUser.setRealName(item.getRealName());
            syncUser.setSex(item.getSex() != null ? SexEnum.parseName(item.getSex()) : null);
            syncUser.setChannel(RecruitUserConstant.RecruitChannelEnum.valueOfName(item.getChannel()));
            syncUser.setAge(item.getAge());
            syncUser.setEducation(RecruitUserConstant.EducationEnum.valueOfName(item.getEducation()));
            syncUser.setTechnicalLevel(RecruitUserConstant.TechnicalLevelEnum.valueOfName(item.getTechnicalLevel()));
            syncUser.setTechnologyType(RecruitUserConstant.TechnologyTypeEnum.valueOfName(item.getTechnologyType()));
            syncUser.setPositionType(RecruitPositionConstant.PositionTypeEnum.getNameByType(item.getPositionType()));
            syncUser.setRecruitmentUserId(item.getRecruitUserId().toString());
            return syncUser;
        }).collect(Collectors.toList());

        String jsonData = JSON.toJSONString(syncRecruitUserList);
        log.info("招聘人员同步数据: {}", jsonData);
        return sendPostRequest(jsonData, recruitUser);
    }

    /**
     * 招聘过程同步
     *
     * @return true-同步成功, false-同步失败
     */
    public boolean syncRecruitProces() {
        // 招聘过程列表
        List<HrmRecruitProces> procesList = Optional.ofNullable(recruitProcesService.lambdaQuery().list()).orElse(new ArrayList<>());

        // 岗位列表
        List<HrmRecruitPosition> positionList = Optional.ofNullable(recruitPositionService.lambdaQuery().list()).orElse(new ArrayList<>());
        Map<Long, String> positionMap = positionList.stream()
                .collect(Collectors.toMap(HrmRecruitPosition::getPositionId, HrmRecruitPosition::getPositionName, (v1, v2) -> v1));

        List<SyncRecruitProcesVO> syncProcesList = procesList.stream().map(item -> {
            SyncRecruitProcesVO syncProces = new SyncRecruitProcesVO();
            syncProces.setPlanId(item.getPlanId().toString());
            syncProces.setStartPlanId(item.getRecordId().toString());
            syncProces.setPositionId(item.getPositionId().toString());

            // 查询岗位名称
            if (positionMap.containsKey(item.getPositionId())) {
                syncProces.setPositionName(positionMap.get(item.getPositionId()));
            }

            syncProces.setRegistrationNum(item.getRegistrationNum());
            syncProces.setWrittenNum(item.getWrittenNum());
            syncProces.setIsWrittenExam(PositionProcessIsEnum.getNameByValue(item.getIsWrittenExam()));
            syncProces.setInterviewNum(item.getInterviewNum());
            syncProces.setIsInterviewExam(PositionProcessIsEnum.getNameByValue(item.getIsInterviewExam()));
            syncProces.setCheckNum(item.getCheckNum());
            syncProces.setEstimateNum(item.getEstimateNum());
            syncProces.setProcesId(item.getProcesId().toString());
            return syncProces;
        }).collect(Collectors.toList());

        String jsonData = JSON.toJSONString(syncProcesList);
        log.info("招聘过程同步数据: {}", jsonData);
        return sendPostRequest(jsonData, proces);
    }

    /**
     * 启动岗位同步
     *
     * @return true-同步成功, false-同步失败
     */
    public boolean syncStartPosition() {
        // 启动岗位
        List<HrmRecruitStartPosition> startPositionList = Optional.ofNullable(recruitStartPositionService.lambdaQuery().list()).orElse(new ArrayList<>());
        //岗位列表
        List<HrmRecruitPosition> positionList = Optional.ofNullable(recruitPositionService.lambdaQuery().list()).orElse(new ArrayList<>());
        Map<Long, String> positionMap = positionList.stream().collect(Collectors.toMap(HrmRecruitPosition::getPositionId, HrmRecruitPosition::getPositionName, (v1, v2) -> v1));

        List<SyncRecruitStartPositionVO> syncStartPositionList = startPositionList.stream().map(item -> {
            SyncRecruitStartPositionVO syncStartPosition = new SyncRecruitStartPositionVO();
            syncStartPosition.setPlanId(item.getPlanId().toString());
            syncStartPosition.setStartPlanId(item.getRecordId().toString());
            syncStartPosition.setPositionId(item.getPositionId().toString());
            // 查询岗位名称
            if (positionMap.containsKey(item.getPositionId())) {
                syncStartPosition.setPositionName(positionMap.get(item.getPositionId()));
            }
            syncStartPosition.setPositionNum(item.getPositionNum());
            syncStartPosition.setPositionDuty(item.getPositionDuty());
            syncStartPosition.setConditionRequire(item.getConditionRequire());
            syncStartPosition.setSalary(item.getSalary());
            syncStartPosition.setWorkLocation(item.getWorkLocation());
            syncStartPosition.setContactUser(item.getContactUser());
            syncStartPosition.setContactPhone(item.getContactPhone());
            syncStartPosition.setStartPositionId(item.getStartPositionId().toString());
            return syncStartPosition;
        }).collect(Collectors.toList());

        String jsonData = JSON.toJSONString(syncStartPositionList);
        log.info("启动岗位同步数据: {}", jsonData);
        return sendPostRequest(jsonData, startPosition);
    }

    /**
     * 招聘记录同步
     *
     * @return true-同步成功, false-同步失败
     */
    public boolean syncPlanRecord() {
        List<HrmRecruitPlanRecord> recordList = Optional.ofNullable(recruitPlanRecordService.lambdaQuery().list()).orElse(new ArrayList<>());

        List<SyncRecruitPlanRecordVO> syncRecordList = recordList.stream().map(item -> {
            SyncRecruitPlanRecordVO syncRecord = new SyncRecruitPlanRecordVO();
            syncRecord.setPlanId(item.getPlanId().toString());
            syncRecord.setStartPlanId(item.getRecordId().toString());
            return syncRecord;
        }).collect(Collectors.toList());

        String jsonData = JSON.toJSONString(syncRecordList);
        log.info("招聘记录同步数据: {}", jsonData);
        return sendPostRequest(jsonData, record);
    }

    /**
     * 招聘计划同步
     *
     * @param planId 计划ID
     * @return true-同步成功, false-同步失败
     */
    public boolean syncPlan(Long planId) {
        SyncRecruitPlanVO syncRecruitPlan = recruitPlanMapper.selectSyncRecruitPlan(planId);

        if (syncRecruitPlan != null) {
            syncRecruitPlan.setCallbackUrl(callbackUrl);
            List<SyncRecruitPlanVO> planList = new ArrayList<>(Collections.singleton(syncRecruitPlan));
            String jsonData = JSON.toJSONString(planList);
            log.info("招聘计划同步数据: {}", jsonData);
            boolean b = sendPostRequest(jsonData, plan);
            if (b) {
                // 计划上报成功 上报计划岗位
                log.info("招聘计划上报成功，开始上报计划岗位");
                return syncPlanPosition(planId);
            }
            return false;
        } else {
            log.info("没有需要同步的招聘计划数据");
            return false;
        }
    }


    /**
     * 招聘计划岗位同步
     *
     * @param planId 计划ID
     * @return true-同步成功, false-同步失败
     */
    private boolean syncPlanPosition(Long planId) {
        List<HrmRecruitPosition> hrmPositionList = Optional.ofNullable(recruitPositionService.lambdaQuery().eq(HrmRecruitPosition::getPlanId, planId).list()).orElse(new ArrayList<>());

        List<SyncRecruitPositionVO> syncPositionList = hrmPositionList.stream().map(item -> {
            SyncRecruitPositionVO syncRecruitPosition = new SyncRecruitPositionVO();
            syncRecruitPosition.setPositionId(item.getPositionId().toString());
            syncRecruitPosition.setPositionName(item.getPositionName());
            syncRecruitPosition.setPositionReason(item.getPositionReason());
            syncRecruitPosition.setPositionNum(item.getPositionNum());
            syncRecruitPosition.setPositionCondition(item.getPositionCondition());
            syncRecruitPosition.setPositionType(RecruitPositionConstant.PositionTypeEnum.getNameByType(item.getPositionType()));
            syncRecruitPosition.setPositionChannel(RecruitPositionConstant.PositionChannelEnum.getNameByChannel(item.getPositionChannel()));
            syncRecruitPosition.setPositionUnit(item.getPositionUnit());
            syncRecruitPosition.setPlanId(item.getPlanId().toString());
            syncRecruitPosition.setPlanPositionId(item.getPositionId().toString());
            return syncRecruitPosition;
        }).collect(Collectors.toList());

        String jsonData = JSON.toJSONString(syncPositionList);
        log.info("招聘岗位同步数据: {}", jsonData);
        return sendPostRequest(jsonData, position);
    }

    /**
     * 工作经历同步
     */
    @Scheduled(cron = "0 30 6 * * ? ")
    public boolean syncWorkExperience() {
        List<SyncWorkExperienceVO> workList = Optional.ofNullable(employeeMapper.selectSyncWorkExperience()).orElse(new ArrayList<>());

        String jsonData = JSON.toJSONString(workList);
        log.info("工作经历同步数据: {}", jsonData);
        return sendPostRequest(jsonData, workUrl);
    }

    /**
     * 教育经历同步
     */
    @Scheduled(cron = "0 30 6 * * ? ")
    public boolean syncEducationExperience() {
        List<SyncEducationExperienceVO> educationList = Optional.ofNullable(employeeMapper.selectSyncEducationExperience()).orElse(new ArrayList<>());

        String jsonData = JSON.toJSONString(educationList);
        log.info("教育经历同步数据: {}", jsonData);
        return sendPostRequest(jsonData, educationUrl);
    }

    /**
     * 岗位同步
     */
    @Scheduled(cron = "0 30 5 * * ? ")
    public boolean syncPostInformation() {
        List<SyncPostInformationVO> postList = Optional.ofNullable(employeeMapper.selectSyncPostInformation()).orElse(new ArrayList<>());

        String jsonData = JSON.toJSONString(postList);
        log.info("岗位同步数据: {}", jsonData);
        return sendPostRequest(jsonData, postUrl);
    }

    /**
     * 员工同步
     */
    @Scheduled(cron = "0 30 4 * * ? ")
    public boolean syncEmployeeInformation() {
        // 所有的员工
        List<HrmEmployee> employeeList = employeeMapper.selectSyncEmployeeInformation();
        //查询员工自定义字段
        List<HrmEmployeeData> hrmEmployeeData = employeeDataService.lambdaQuery().list();
        Map<Long, Map<String, String>> dataMap = new HashMap<>();
        if (hrmEmployeeData != null && !hrmEmployeeData.isEmpty()) {
            dataMap = hrmEmployeeData.stream()
                    .filter(data -> StrUtil.isNotEmpty(data.getFieldName()) && StrUtil.isNotEmpty(data.getFieldValue()))
                    .collect(Collectors.groupingBy(
                            HrmEmployeeData::getEmployeeId,
                            Collectors.toMap(HrmEmployeeData::getFieldName, HrmEmployeeData::getFieldValue, (v1, v2) -> v1)
                    ));
        }
        //执业职格
        List<HrmEmployeeCertificate> certificateList = certificateService.lambdaQuery().list();
        Map<Long, List<HrmEmployeeCertificate>> certificateGroup = new HashMap<>();
        if (certificateList != null && !certificateList.isEmpty()) {
            certificateGroup = certificateList.stream().collect(Collectors.groupingBy(HrmEmployeeCertificate::getEmployeeId));
        }
        // 员工教育经历
        List<HrmEmployeeEducationExperience> educationList = educationExperienceService.lambdaQuery().list();
        Map<Long, List<HrmEmployeeEducationExperience>> educationGroup = new HashMap<>();
        if (educationList != null && !educationList.isEmpty()) {
            educationGroup = educationList.stream().collect(Collectors.groupingBy(HrmEmployeeEducationExperience::getEmployeeId));
        }
        // 专业技术资格
        List<HrmEmployeeTechnical> technicalList = employeeTechnicalService.lambdaQuery().list();
        Map<Long, List<HrmEmployeeTechnical>> technicalGroup = new HashMap<>();
        if (technicalList != null && !technicalList.isEmpty()) {
            technicalGroup = technicalList.stream().collect(Collectors.groupingBy(HrmEmployeeTechnical::getEmployeeId));
        }

        List<SyncEmployeeInformationVO> syncEmployeeList = new ArrayList<>();
        if (employeeList != null && !employeeList.isEmpty()) {
            for (HrmEmployee employee : employeeList) {
                //自定义数据
                Map<String, String> data = dataMap.getOrDefault(employee.getEmployeeId(), new HashMap<>());
                // 执业职格
                List<HrmEmployeeCertificate> certificates = certificateGroup.getOrDefault(employee.getEmployeeId(), new ArrayList<>());
                //教育经历
                List<HrmEmployeeEducationExperience> educations = educationGroup.getOrDefault(employee.getEmployeeId(), new ArrayList<>());
                //专业技术资格
                List<HrmEmployeeTechnical> technicals = technicalGroup.getOrDefault(employee.getEmployeeId(), new ArrayList<>());

                SyncEmployeeInformationVO syncEmployee = new SyncEmployeeInformationVO();
                syncEmployee.setEmployeeId(employee.getEmployeeId().toString());
                syncEmployee.setEmployeeName(employee.getEmployeeName());
                if (employee.getSex() != null) {
                    syncEmployee.setSex(EmployeeSexEnum.parseName(employee.getSex()));
                }
                if (employee.getDateOfBirth() != null) {
                    LocalDate dateOfBirth = employee.getDateOfBirth();
                    String formattedDate = dateOfBirth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                    syncEmployee.setDateOfBirth(formattedDate);
                }
                syncEmployee.setNation(employee.getNation());
                syncEmployee.setPolName(data.get("pol_id"));
                syncEmployee.setPolTime(data.get("pol_time"));
                syncEmployee.setJoinWorkTime(data.get("join_work_time"));
                syncEmployee.setHighestEducation(EducationEnum.getNameByValue(employee.getHighestEducation()));
                syncEmployee.setHighestDegree(data.get("highest_degree"));
                if (educations != null && !educations.isEmpty()) {
                    // 获取全日制教育经历
                    List<HrmEmployeeEducationExperience> fullTimeEducations = educations.stream()
                            .filter(education -> Objects.equals(education.getTeachingMethods(), TeachingMethodEnum.ONE.getValue()))
                            .collect(Collectors.toList());

                    // 获取非全日制教育经历
                    List<HrmEmployeeEducationExperience> partTimeEducations = educations.stream()
                            .filter(education -> !Objects.equals(education.getTeachingMethods(), TeachingMethodEnum.ONE.getValue()))
                            .collect(Collectors.toList());

                    // 获取全日制最高学历学位、学校、专业
                    if (!fullTimeEducations.isEmpty()) {
                        HrmEmployeeEducationExperience highestFullTime = getHighestEducation(fullTimeEducations);
                        if (highestFullTime != null) {
                            // 设置全日制学历学位
                            String fullTimeDegree = buildEducationDegreeString(highestFullTime);
                            syncEmployee.setFullTimeDegree(fullTimeDegree);

                            // 设置全日制毕业院校及专业
                            String fullTimeSchool = buildSchoolMajorString(highestFullTime);
                            syncEmployee.setFullTimeSchool(fullTimeSchool);
                        }
                    }

                    // 获取非全日制最高学历学位、学校、专业
                    if (!partTimeEducations.isEmpty()) {
                        HrmEmployeeEducationExperience highestPartTime = getHighestEducation(partTimeEducations);
                        if (highestPartTime != null) {
                            // 设置在职学历学位
                            String onJobDegree = buildEducationDegreeString(highestPartTime);
                            syncEmployee.setOnJobDegree(onJobDegree);

                            // 设置在职毕业院校及专业
                            String onJobSchool = buildSchoolMajorString(highestPartTime);
                            syncEmployee.setOnJobSchool(onJobSchool);
                        }
                    }
                }
                // 最高职称级别
                String highestTechLevel = null;
                if (technicals != null && !technicals.isEmpty()) {
                    HrmEmployeeTechnical highest = getHighestTechnical(technicals);
                    highestTechLevel = buildHighestTechLevelString(highest);
                }
                if (StrUtil.isEmpty(highestTechLevel)) {
                    highestTechLevel = data.get("highest_tech_title");
                }
                syncEmployee.setHighestTechLevel(highestTechLevel);
                syncEmployee.setAssessmentResult(data.get("assessment_result"));
                syncEmployee.setPositionType(data.get("position_type"));
                syncEmployee.setHonoraryTitle(data.get("honorary_title"));
                syncEmployee.setHonoraryName(data.get("honorary_name"));
                syncEmployee.setHonoraryDate(data.get("honorary_date"));
                syncEmployee.setEmployeeLevel(data.get("employee_level"));
                if (certificates != null && !certificates.isEmpty()) {
                    String str = certificates.stream().map(HrmEmployeeCertificate::getCertificateName).filter(StrUtil::isNotEmpty).collect(Collectors.joining("/"));
                    syncEmployee.setProfessionalQualification(str);
                }

                // 添加需要同步的人员数据
                syncEmployeeList.add(syncEmployee);
            }
        }
        // 推送员工数据
        String jsonData = JSON.toJSONString(syncEmployeeList);
        log.info("员工数据同步开始:{}", jsonData);

        return sendPostRequest(jsonData, employeeUrl);
    }

    /**
     * 部门同步
     */
    @Scheduled(cron = "0 30 3 * * ? ")
    public boolean syncDeptInformation() {
        // 获取所有部门
        List<SyncDeptTreeVO> deptTreeList = deptMapper.selectSyncDeptList();
        Map<Long, List<SyncDeptTreeVO>> deptGroup = new HashMap<>();
        if (deptTreeList != null && !deptTreeList.isEmpty()) {
            deptGroup = deptTreeList.stream().collect(Collectors.groupingBy(SyncDeptTreeVO::getParentId));
        }
        // 获取所有的员工
        List<EmployeePostInformationVo> employeeList = employeeMapper.getEmployeePostList();
        Map<Long, List<EmployeePostInformationVo>> employeeGroup = new HashMap<>();
        if (employeeList != null && !employeeList.isEmpty()) {
            employeeGroup = employeeList.stream().collect(Collectors.groupingBy(EmployeePostInformationVo::getDeptId));
        }

        List<SyncDeptTreeVO> rootDept = Optional.ofNullable(deptGroup.get(0L)).orElse(new ArrayList<>());

        // 处理每个部门，生成SyncDeptInformationVO统计数据
        List<SyncDeptInformationVO> syncDeptInfoList = new ArrayList<>();

        for (SyncDeptTreeVO dept : rootDept) {
            processDeptStatistics(dept, deptGroup, employeeGroup, syncDeptInfoList);
        }

        // 这里可以添加保存或推送逻辑
        log.info("部门统计数据生成完成，共处理{}个部门", syncDeptInfoList.size());
        String jsonData = JSON.toJSONString(syncDeptInfoList);

        return sendPostRequest(jsonData, deptUrl);
    }

    /**
     * 发送post的请求
     *
     * @param jsonData 要发送的JSON数据
     * @param url      目标URL
     * @return true-成功, false-失败
     */
    private boolean sendPostRequest(String jsonData, String url) {
        if (StrUtil.isEmpty(jsonData)) {
            return false;
        }
        // 接口推送
        try {

            DataForEncoder encoder = DataEncoderFactory.factory(algorithm);
            if (encoder == null) {
                log.error("不支持的加密算法: {}", algorithm);
                return false;
            }
            String encryptData = encoder.dataEncryption(jsonData, secretKey);

            // 构建请求参数
            Map<String, String> params = new HashMap<>();
            params.put("encryptData", encryptData);
            params.put("sourceId", sourceId);

            // 发送POST请求
            String response = HttpUtil.post(url, JSON.toJSONString(params));

            log.info("数据同步响应: {}", response);

            // 解析响应结果
            if (StrUtil.isNotEmpty(response)) {
                com.alibaba.fastjson2.JSONObject jsonResponse = JSON.parseObject(response);
                Integer code = jsonResponse.getInteger("code");
                String msg = jsonResponse.getString("msg");

                if (code != null && code == 200) {
                    log.info("数据同步成功: {}", msg);
                    return true;
                } else {
                    log.error("数据同步失败, code: {}, msg: {}", code, msg);
                    return false;
                }
            }

            return false;

        } catch (Exception e) {
            log.error("数据同步异常: {}", e.getMessage(), e);
            return false;
        }
    }


    /**
     * 处理单个部门的统计数据
     */
    private void processDeptStatistics(SyncDeptTreeVO dept,
                                       Map<Long, List<SyncDeptTreeVO>> deptGroup,
                                       Map<Long, List<EmployeePostInformationVo>> employeeGroup,
                                       List<SyncDeptInformationVO> syncDeptInfoList) {

        List<EmployeePostInformationVo> employees = employeeGroup.getOrDefault(dept.getDeptId(), new ArrayList<>());
        // 现有人数
        dept.setCurrentNum(employees.size());

        // 正式员工
        long count = employees.stream().filter(emp -> "劳动合同工".equals(emp.getWorkForms())).count();
        dept.setRegularNum((int) count);

        // 设置正处级数据
        long zcCurrentNumTotal = employees.stream().filter(emp -> "比照正县".equals(emp.getEmployeeLevel())).count();
        if (dept.getDeptType() == HrmDeptTypeEnum.COMPANY.getValue()) {
            dept.setSectionChiefPreparation(0);
        } else {
            dept.setSectionChiefPreparation(dept.getSectionChiefPreparation() == null ? 0 : dept.getSectionChiefPreparation());
        }
        dept.setSectionChiefNum((int) zcCurrentNumTotal);

        // 设置副处级数据
        long fcCurrentNumTotal = employees.stream().filter(emp -> "比照副县".equals(emp.getEmployeeLevel())).count();
        if (dept.getDeptType() == HrmDeptTypeEnum.COMPANY.getValue()) {
            dept.setDeputySectionChiefPreparation(0);
        } else {
            dept.setDeputySectionChiefPreparation(dept.getDeputySectionChiefPreparation() == null ? 0 : dept.getDeputySectionChiefPreparation());
        }
        dept.setDeputySectionChiefNum((int) fcCurrentNumTotal);

        // 设置正科级数据
        long zkCurrentNumTotal = employees.stream().filter(emp -> "比照正科".equals(emp.getEmployeeLevel())).count();
        if (dept.getDeptType() == HrmDeptTypeEnum.COMPANY.getValue()) {
            dept.setDirectorPreparation(0);
        } else {
            dept.setDirectorPreparation(dept.getDirectorPreparation() == null ? 0 : dept.getDirectorPreparation());
        }
        dept.setDirectorNum((int) zkCurrentNumTotal);

        // 设置副科级数据
        long fkCurrentNumTotal = employees.stream().filter(emp -> "比照副科".equals(emp.getEmployeeLevel())).count();
        if (dept.getDeptType() == HrmDeptTypeEnum.COMPANY.getValue()) {
            dept.setDeputyDirectorPreparation(0);
        } else {
            dept.setDeputyDirectorPreparation(dept.getDeputyDirectorPreparation() == null ? 0 : dept.getDeputyDirectorPreparation());
        }
        dept.setDeputyDirectorNum((int) fkCurrentNumTotal);

        // 设置基本信息
        SyncDeptInformationVO syncDeptInfo = new SyncDeptInformationVO();
        syncDeptInfo.setDeptId(String.valueOf(dept.getDeptId()));
        syncDeptInfo.setDeptName(dept.getDeptName());
        syncDeptInfo.setSortId(dept.getSortId());
        syncDeptInfo.setDeptType(dept.getDeptType() == 1 ? "公司" : "部门");
        syncDeptInfo.setParentId(String.valueOf(dept.getParentId()));
        syncDeptInfo.setMainEmployeeId(dept.getMainEmployeeId() != null ? String.valueOf(dept.getMainEmployeeId()) : null);
        syncDeptInfo.setMainEmployeePhone(dept.getMainEmployeePhone());
        syncDeptInfo.setUnitNature(OrgTypeEnum.getNameByValue(dept.getOrgType()));

        // 子级部门
        List<SyncDeptTreeVO> deptTreeVOList = deptGroup.get(dept.getDeptId());

        if (deptTreeVOList != null && !deptTreeVOList.isEmpty()) {
            for (SyncDeptTreeVO childDept : deptTreeVOList) {
                processDeptStatistics(childDept, deptGroup, employeeGroup, syncDeptInfoList);
            }

            int currentNum = 0;
            int regularNum = 0;
            int zcConfigNum = 0;
            int zcCurrentNum = 0;
            int fcConfigNum = 0;
            int fcCurrentNum = 0;
            int zkConfigNum = 0;
            int zkCurrentNum = 0;
            int fkConfigNum = 0;
            int fkCurrentNum = 0;
            // 把所有的子部门数据合并到父部门数据中
            for (SyncDeptTreeVO syncDeptTreeVO : deptTreeVOList) {
                currentNum += syncDeptTreeVO.getCurrentNum();
                regularNum += syncDeptTreeVO.getRegularNum();
                zcConfigNum += syncDeptTreeVO.getSectionChiefPreparation();
                zcCurrentNum += syncDeptTreeVO.getSectionChiefNum();
                fcConfigNum += syncDeptTreeVO.getDeputySectionChiefPreparation();
                fcCurrentNum += syncDeptTreeVO.getDeputySectionChiefNum();
                zkConfigNum += syncDeptTreeVO.getDirectorPreparation();
                zkCurrentNum += syncDeptTreeVO.getDirectorNum();
                fkConfigNum += syncDeptTreeVO.getDeputyDirectorPreparation();
                fkCurrentNum += syncDeptTreeVO.getDeputyDirectorNum();
            }
            dept.setCurrentNum(dept.getCurrentNum() + currentNum);
            dept.setRegularNum(dept.getRegularNum() + regularNum);
            dept.setSectionChiefPreparation(dept.getSectionChiefPreparation() + zcConfigNum);
            dept.setSectionChiefNum(dept.getSectionChiefNum() + zcCurrentNum);
            dept.setDeputySectionChiefPreparation(dept.getDeputySectionChiefPreparation() + fcConfigNum);
            dept.setDeputySectionChiefNum(dept.getDeputySectionChiefNum() + fcCurrentNum);
            dept.setDirectorPreparation(dept.getDirectorPreparation() + zkConfigNum);
            dept.setDirectorNum(dept.getDirectorNum() + zkCurrentNum);
            dept.setDeputyDirectorPreparation(dept.getDeputyDirectorPreparation() + fkConfigNum);
            dept.setDeputyDirectorNum(dept.getDeputyDirectorNum() + fkCurrentNum);
        }
        syncDeptInfo.setCurrentNum(dept.getCurrentNum());
        syncDeptInfo.setRegularNum(dept.getRegularNum());
        syncDeptInfo.setSectionChiefPreparation(dept.getSectionChiefPreparation());
        syncDeptInfo.setSectionChiefNum(dept.getSectionChiefNum());
        syncDeptInfo.setDeputySectionChiefPreparation(dept.getDeputySectionChiefPreparation());
        syncDeptInfo.setDeputySectionChiefNum(dept.getDeputySectionChiefNum());
        syncDeptInfo.setDirectorPreparation(dept.getDirectorPreparation());
        syncDeptInfo.setDirectorNum(dept.getDirectorNum());
        syncDeptInfo.setDeputyDirectorPreparation(dept.getDeputyDirectorPreparation());
        syncDeptInfo.setDeputyDirectorNum(dept.getDeputyDirectorNum());
        syncDeptInfoList.add(syncDeptInfo);

    }

    /**
     * 获取最高学历的教育经历
     * 只按学历等级排序，取最高者，如果有相同的就随便取一条
     * 学历字段取值范围：1-8
     */
    private HrmEmployeeEducationExperience getHighestEducation(List<HrmEmployeeEducationExperience> educations) {
        if (educations == null || educations.isEmpty()) {
            return null;
        }

        return educations.stream()
                .max((e1, e2) -> {
                    // 只按学历等级比较，学历字段取值范围1-8，数值越大学历越高
                    int education1 = e1.getEducation() != null ? e1.getEducation() : 0;
                    int education2 = e2.getEducation() != null ? e2.getEducation() : 0;

                    // 确保学历值在1-8范围内，超出范围的视为0
                    if (education1 < 1 || education1 > 8) {
                        education1 = 0;
                    }
                    if (education2 < 1 || education2 > 8) {
                        education2 = 0;
                    }

                    return Integer.compare(education1, education2);
                })
                .orElse(null);
    }

    /**
     * 构建学历学位字符串
     */
    private String buildEducationDegreeString(HrmEmployeeEducationExperience education) {
        StringBuilder sb = new StringBuilder();

        // 添加学历
        if (education.getEducation() != null) {
            String educationName = EmployeeEducationEnum.parseName(education.getEducation());
            if (StrUtil.isNotEmpty(educationName)) {
                sb.append(educationName);
            }
        }

        // 添加学位
        if (education.getDegree() != null) {
            String degreeName = DegreeEnum.getNameByValue(education.getDegree());
            if (StrUtil.isNotEmpty(degreeName)) {
                if (sb.length() > 0) {
                    sb.append("/");
                }
                sb.append(degreeName);
            }
        }

        return sb.toString();
    }

    /**
     * 构建学校专业字符串
     */
    private String buildSchoolMajorString(HrmEmployeeEducationExperience education) {
        StringBuilder sb = new StringBuilder();

        // 添加毕业院校
        if (StrUtil.isNotEmpty(education.getGraduateSchool())) {
            sb.append(education.getGraduateSchool());
        }

        // 添加专业
        if (StrUtil.isNotEmpty(education.getMajor())) {
            sb.append(education.getMajor());
        }

        return sb.toString();
    }

    /**
     * 从专业技术资格中选出最高级别
     * 优先级：正高级 > 副高级 > 中级 > 助理级 > 员级 > 无
     * 相同级别任取一条
     */
    private HrmEmployeeTechnical getHighestTechnical(List<HrmEmployeeTechnical> technicals) {
        if (technicals == null || technicals.isEmpty()) {
            return null;
        }
        Map<String, Integer> priority = new HashMap<>();
        priority.put("正高级", 6);
        priority.put("副高级", 5);
        priority.put("中级", 4);
        priority.put("助理级", 3);
        priority.put("员级", 2);
        priority.put("无", 1);

        return technicals.stream()
                .max(Comparator.comparingInt(t -> priority.getOrDefault(safeTrim(t.getTechnicalLevel()), 0)))
                .orElse(null);
    }

    /**
     * 组合最高职称级别显示文案
     * 规则：级别为“无”则直接返回技术职务名称；否则 级别 + "/" + 技术职务名称
     */
    private String buildHighestTechLevelString(HrmEmployeeTechnical technical) {
        if (technical == null) {
            return null;
        }
        String level = safeTrim(technical.getTechnicalLevel());
        String name = safeTrim(technical.getTechnicalName());
        if (StrUtil.isEmpty(level)) {
            return name;
        }
        if ("无".equals(level)) {
            return name;
        }
        if (StrUtil.isEmpty(name)) {
            return level;
        }
        return level + name;
    }

    private String safeTrim(String s) {
        return s == null ? null : s.trim();
    }
}
